/*
 * @Author: silence
 * @Date: 2023-07-04 15:10:26
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-04-15 10:49:45
 * @Description: 电站添加控制器
 */
import 'package:ems_neutral_app/main.dart';
import 'package:ems_neutral_app/pages/Mine/Language/SilLocalizations/SilLocalizations.dart';
import 'package:ems_neutral_app/utils/toast/SilToastExtends.dart';
import 'package:get/get.dart';
import 'package:ems_neutral_app/entities/TimeZoneEntity.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:sil_utils_package/sil_utils_package.dart';

import '../../../api/ApiUtils.dart';
import '../../../api/request/CommonRequest.dart';
import '../../../api/request/PowerStationRequest.dart';
import '../../../bloc/userbloc/user_bloc.dart';
import '../../../config/AppInfo.dart';
import '../../../utils/eventBus/eventBus.dart';
import '../../../utils/string/StringConstant.dart';
import '../../Mine/Language/LanguageController.dart';

class PowerStationAddController extends GetxController {
  // 时区列表
  List<TimeZoneEntity> _timeZoneList = [];
  // List<String> _timeZoneListStr = [];

  /// 获取设备型号
  /// equipmentSelection 设备类型 1高压，2低压
  Future<List<String>> getDeviceModels({int equipmentSelection = 1}) async {
    List<String> models = [];
    if (equipmentSelection == 1) {
      if (AppInfo.highVoltageModels.isEmpty) {
        await requestDeviceModels(
          success: (p0) {
            models = p0;
            AppInfo.highVoltageModels = models;
          },
        );
      } else {
        models = AppInfo.highVoltageModels;
      }
    } else {
      if (AppInfo.lowVoltageModels.isEmpty) {
        List<String> e2LModels = [], e3Modles = [], totalModels = [];
        await requestDeviceModels(
          model: 'E2L',
          success: (p0) => e2LModels = p0,
        );

        await requestDeviceModels(
          model: 'E3',
          success: (p0) => e3Modles = p0,
        );

        totalModels.addAll(e3Modles);
        totalModels.addAll(e2LModels);
        models = totalModels;
        AppInfo.lowVoltageModels = models;
      } else {
        models = AppInfo.lowVoltageModels;
      }
    }

    return models;
  }

  /// 获取产品型号
  /// model 设备类型(高压'E2H'、低压'E2L'、E3'E3')
  requestDeviceModels(
      {dynamic Function(List<String>)? success,
      dynamic Function(List<String>)? failure,
      String model = 'E2H'}) async {
    List<String> modelsList = [];

    await apiShow(navigatorKey.currentState!.context,
        api: api_common_global_config(configName: model), success: (p0) {
      Map map = p0.data as Map;
      if (map.containsKey('configValue')) {
        String models = map['configValue'];
        modelsList = SilTools.stringIsEmpty(models) ? [] : models.split(',');
      }
      if (success != null) success(modelsList);
    }, failure: (p0) {
      if (failure != null) failure(p0);
    }, showLoading: true);
  }

  /// 添加电站
  /// psName 电站名称（同SN码）
  /// snNumber SN码
  /// modelSelection 设备型号
  /// equipmentSelection 设备类型
  /// timeZone 时区
  /// locationLng 经度
  /// locationLat 纬度
  /// createMode 1SN创建，0Wifi
  powerStationAdd({
    required BuildContext context,
    required String snNumber,
    required String modelSelection,
    required int equipmentSelection,
    required int timeZoneIndex,
    required double locationLng,
    required double locationLat,
    String? userId,
    String? key,
    Function(dynamic)? successHandler,
  }) {
    if (SilTools.stringIsEmpty(snNumber)) {
      // PN码不能为空
      SilToastExtends.toastMsg(LangOf(context)?.dzdz2?.SN_noempty);
      return;
    }

    if (SilTools.stringIsEmpty(modelSelection)) {
      // 请选择型号
      SilToastExtends.toastMsg(LangOf(context)?.common?.modelNumber);
      return;
    }

    TimeZoneEntity timeZoneEntity = this._timeZoneList[timeZoneIndex];
    String? timeZone = timeZoneEntity.timeZone;

    if (SilTools.stringIsEmpty(timeZone)) {
      // 时区选择不能为空
      SilToastExtends.toastMsg(LangOf(context)?.dzdz2?.timezone_noempty);
      return;
    }

    apiShow(context,
        api: api_power_station_add(
            psName: snNumber,
            snNumber: snNumber,
            modelSelection: modelSelection,
            equipmentSelection: equipmentSelection,
            timeZoneStr: timeZone!,
            timeZone: int.parse(timeZoneEntity.id ?? '0'),
            locationLng: locationLng,
            locationLat: locationLat,
            userId: userId,
            key: key), success: (res) {
      /// 电站添加成功
      SilToastExtends.toastMsg(LangOf(context)?.dzdz2?.addSuccess);

      /// 没有设备时,返回到主页面
      if (SilTools.stringIsEmpty(UserBlocTool.userEntity?.powerRecordId) ||
          UserBlocTool.userEntity?.powerRecordId == '0') {
        bus.emit(StringConstant.PowerStationsFirstAdded);
      } else {
        if (successHandler != null) successHandler(res);

        /// 电站数量放生了变化
        bus.emit(StringConstant.PowerStationsNumChange);
      }
    }, showLoading: true);
  }

  /// 获取时区列表
  getTimeZoneList({
    required BuildContext context,
    Function(dynamic)? successHandler,
  }) {
    if (SilTools.listIsEmpty(this._timeZoneList) == false) {
      if (successHandler != null) successHandler(this._timeZoneList);
      return;
    }

    apiShow(context, api: api_time_zone_list(), success: (res) {
      this._timeZoneList = res.data;
      if (successHandler != null) successHandler(this._timeZoneList);
    }, showErrorToast: false);
  }

  /// 获取时区名称列表
  getTimeZoneNameList({
    required BuildContext context,
    Function(dynamic)? successHandler,
  }) {
    getTimeZoneList(
      context: context,
      successHandler: (p0) {
        List result = p0 as List;
        List<String> list;
        // 根据当前语言判断
        LanguageController languageController = LanguageController();
        bool isEnglish = languageController.isPromptEnglish();
        if (isEnglish == false) {
          list = result.map<String>((e) => e.timeZoneName).toList();
        } else {
          list = result.map<String>((e) => e.timeZoneNameEn).toList();
        }

        if (successHandler != null) successHandler(list);
      },
    );
  }

  /// 根据时区名称，获取时区id
  int get_time_zone_id(String timeZoneName) {
    for (TimeZoneEntity element in this._timeZoneList) {
      if (element.timeZoneName == timeZoneName) {
        return int.parse(element.id ?? '0');
      }
    }

    return 0;
  }

  /// 获取定位
  Future<Position?> getLocation() async {
    bool serviceEnabled;
    LocationPermission permission;

    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      return Future.error('Location services are disabled.');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        return null;
      }
    }

    if (permission == LocationPermission.deniedForever) {
      return null;
    }
    return await Geolocator.getCurrentPosition();
  }

  /// 识别扫描后的SN码、key
  List<String> recognitionScanSNCode(String? scanString) {
    List<String> list = ["", ""];
    String snCode = "", key = "";

    // 思道尔二维码：SN:E47W 2350 2860 KEY:JR3F EDFL
    if (scanString!.contains('KEY:') &&
        scanString.contains('SN:') &&
        scanString.length >= 12) {
      snCode = scanString.substring(3, 17);
      snCode = snCode.replaceAll(new RegExp(r"\s+\b|\b\s"), ""); // 去除空格
      key = scanString.substring(22, 31);
      key = key.replaceAll(new RegExp(r"\s+\b|\b\s"), ""); // 去除空格
    } else {
      snCode = scanString;
    }

    list[0] = snCode;
    list[1] = key;

    return list;
  }

  /// 验证是不是思道尔设备
  bool isSDErDevice(String? snCode) {
    if (snCode?.length != 12) {
      return false;
    }

    List<String> startsList = [
      "B",
      "D",
      "E",
    ];
    String starts = snCode!.substring(0, 1);
    if (startsList.contains(starts)) {
      return true;
    }

    return false;
  }
}
